package com.example.tao.mycar.fragment;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.avos.avoscloud.AVUser;
import com.example.tao.mycar.MyApplication;
import com.example.tao.mycar.R;
import com.example.tao.mycar.database.OperateDBUtils;
import com.example.tao.mycar.entity.PersonDataEntity;
import com.example.tao.mycar.utils.RequestUtils;
import com.example.tao.mycar.utils.Tools;
import com.example.tao.mycar.view.arcview.UserInfoModel;
import com.example.tao.mycar.view.arcview.WeightArcView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link WeightViewFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link WeightViewFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class WeightViewFragment extends Fragment implements RequestUtils.UserWeightChangeListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private ArrayList<PersonDataEntity> timeWeightDataArray = new ArrayList<>();
    private WeightLineChartFragment weightLineChartFragment;
    private final Object object = new Object();
    private WeightArcView mWeightArcView;
    private LinearLayout linearLayout;
    private double oldTotalMin = 0.0;
    private double newTotalMin = 0.0;

    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment WeightViewFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static WeightViewFragment newInstance(String param1, String param2) {
        WeightViewFragment fragment = new WeightViewFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public WeightViewFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        timeWeightDataArray = MyApplication.getInstance().getUserWeightData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_weightinfo, container, false);
        mWeightArcView = ((WeightArcView) view.findViewById(R.id.panel));
        mWeightArcView.setDataModel(getData());
        weightLineChartFragment = WeightLineChartFragment.newInstance("", "");
        weightLineChartFragment.setTimeWeightDataArray(timeWeightDataArray);
        getFragmentManager().beginTransaction().replace(R.id.curve_fragment, weightLineChartFragment).commitAllowingStateLoss();
        RequestUtils requestUtils = new RequestUtils(getContext());
        requestUtils.setUserWeightChangeListener(this);
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    private UserInfoModel getData() {
        UserInfoModel model = new UserInfoModel();
        String weightNum = RequestUtils.getSharedPreference(getContext()).getString(RequestUtils.BABYWEIGHT, "0");
        Log.d("ZZ", "weightNum = " + weightNum);
        if (Tools.isNumericOrDot(weightNum)) {
            newTotalMin = Double.parseDouble(weightNum);
            model.setUserTotal(newTotalMin);
        } else {
            model.setUserTotal(0);
        }
        model.setAssess("体重良好");
        model.setTotalMin(oldTotalMin);
        Log.d("ZZ", "oldTotalMin = " + oldTotalMin);
        oldTotalMin = newTotalMin;
        double lowWeight = 15;
        double highWeight = 18.6;
        model.setTotalMax(lowWeight + highWeight);
        model.setFourText("标准 : " + lowWeight + "kg - " + highWeight + "kg");
        return model;
    }

    @Override
    public void userWeightChange() {
        queryUserWeightData();
    }

    private void queryUserWeightData() {

        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                synchronized(object) {
                    Cursor cursor = null;
                    try {
                        String columns[] = new String[]{OperateDBUtils.TIME, OperateDBUtils.USER_ID, OperateDBUtils.WEIGHT};
                        String selection = OperateDBUtils.USER_ID + "=?";
                        cursor = getContext().getContentResolver().query(OperateDBUtils.WEIGHT_URI, columns, selection,
                                new String[]{AVUser.getCurrentUser().getObjectId()}, null);
                        timeWeightDataArray.clear();
                        Tools.SortArrayList sort = new Tools.SortArrayList();
                        if (cursor != null && cursor.getCount() > 0) {
                            while (cursor.moveToNext()) {
                                String timePoint = cursor.getString(cursor.getColumnIndex(OperateDBUtils.TIME));
                                String weightNum = cursor.getString(cursor.getColumnIndex(OperateDBUtils.WEIGHT));
                                timePoint = Tools.getYearFromDatePicker(timePoint) + "-" +
                                        Tools.getMonthFromDatePicker(timePoint) + "-" +
                                        Tools.getDayFromDatePicker(timePoint);
                                PersonDataEntity personDataEntity = new PersonDataEntity();
                                personDataEntity.setTime(timePoint);
                                personDataEntity.setWeight(weightNum);
                                timeWeightDataArray.add(personDataEntity);
                                Log.d("ZZ", "weightNum = " + weightNum);
                                Log.d("ZZ", "timePoint = " + timePoint);
                            }
                            Collections.sort(timeWeightDataArray, sort);
                        }
                        if (timeWeightDataArray.size() > 0) {
                            RequestUtils.getSharedPreferenceEditor(getContext()).putString(RequestUtils.BABYWEIGHT,
                                    timeWeightDataArray.get(timeWeightDataArray.size() - 1).getWeight()).commit();
                        } else {
                            RequestUtils.getSharedPreferenceEditor(getContext()).putString(RequestUtils.BABYWEIGHT,
                                    "0").commit();
                        }
                        handler.sendEmptyMessage(0x01);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (cursor != null) {
                            cursor.close();
                        }
                    }
                }
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x01) {
                mWeightArcView.setDataModel(getData());
                mWeightArcView.invalidate();
                WeightLineChartFragment newWeightBarCharFragment = WeightLineChartFragment.newInstance("", "");
                Log.d("ZZ", "timeWeightDataArray --> size = " + timeWeightDataArray.size());
                newWeightBarCharFragment.setTimeWeightDataArray(timeWeightDataArray);

                getFragmentManager().beginTransaction().remove(weightLineChartFragment).commitAllowingStateLoss();
                getFragmentManager().beginTransaction().replace(R.id.curve_fragment, newWeightBarCharFragment).commitAllowingStateLoss();
            }
        }
    };

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

}
